package com.letoken.platform.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.admin.service.AdminMallService;
import com.letoken.platform.pub.constant.ConstantsValue;
import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.enums.*;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.util.DateUtil;
import com.letoken.platform.repo.admin.dao.AdminCardConfigMapper;
import com.letoken.platform.repo.admin.po.AdminCardConfig;
import com.letoken.platform.repo.admin.req.mall.*;
import com.letoken.platform.repo.admin.res.mall.*;
import com.letoken.platform.repo.app.dao.AppUserAssetsHistoryMapper;
import com.letoken.platform.repo.app.dao.AppUserMapper;
import com.letoken.platform.repo.app.dao.AppUserWalletMapper;
import com.letoken.platform.repo.app.dao.TokenMapper;
import com.letoken.platform.repo.app.po.AppUser;
import com.letoken.platform.repo.app.po.AppUserAssetsHistory;
import com.letoken.platform.repo.app.po.AppUserWallet;
import com.letoken.platform.repo.app.po.Token;
import com.letoken.platform.repo.app.redis.AppLoginTokenRedis;
import com.letoken.platform.repo.mall.dao.*;
import com.letoken.platform.repo.mall.po.*;
import com.letoken.platform.repo.utlis.PageDataUtil;
import com.letoken.platform.repo.utlis.UniqueIDUtils;
import com.letoken.platform.repo.utlis.lock.Lock;
import com.letoken.platform.repo.utlis.lock.LockCategoryEnum;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author letokenlabs
 * @date 2022/11/23$
 */
@Service
@Log4j2
public class AdminMallServiceImpl implements AdminMallService {
    @Autowired
    AppMallInfoMapper appMallInfoMapper;
    @Autowired
    AppMallAuditMapper appMallAuditMapper;
    @Autowired
    AppMallAccountMapper appMallAccountMapper;
    @Autowired
    AppMallStatisticsMapper appMallStatisticsMapper;
    @Autowired
    AppMallBannerMapper appMallBannerMapper;
    @Autowired
    StringRedisTemplate redisService;
    @Autowired
    AdminMallPromotionMapper adminMallPromotionMapper;
    @Autowired
    AppUserMapper appUserMapper;
    @Autowired
    AppMallPromotionMapper appMallPromotionMapper;
    @Autowired
    LevelUpHistoryMapper levelUpHistoryMapper;
    @Autowired
    AppMallPromotionIdsMapper appMallPromotionIdsMapper;
    @Autowired
    AppMallDocumentInfoMapper appMallDocumentInfoMapper;
    @Autowired
    TokenMapper tokenMapper;
    @Autowired
    AppUserWalletMapper appUserWalletMapper;
    @Resource
    private AdminCardConfigMapper adminCardConfigMapper;

    @Resource
    private AppMallCardInfoMapper appMallCardInfoMapper;
    @Autowired
    AdminMallConfigMapper adminMallConfigMapper;





    @Override
    public PageData<QueryMallStoreAuditListRes> queryMallStoreAuditList(QueryMallStoreAuditListReq req) {
        Page<QueryMallStoreAuditListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryMallStoreAuditListRes> res = appMallAuditMapper.getAuditRecord(page,req);
        if (!CollectionUtils.isEmpty(res.getRecords())){
            res.getRecords().forEach(x->{
                if (ConstantsValue.I_3.equals(x.getAuditType()) && StringUtils.isNotBlank(x.getSourceData())){
                    x.setBgImage(null);
                    x.setMallAddress(null);
                    x.setLogo(null);
                    x.setPhone(null);
                    x.setOneCategory(null);
                    x.setTwoCategory(null);
                    x.setOneCategoryName(null);
                    x.setTwoCategoryName(null);

                    AppMallDocumentInfo j = JSONObject.parseObject(x.getSourceData(),AppMallDocumentInfo.class);
                    if (ObjectUtils.isNotEmpty(j)){
                        x.setName(j.getName());
                        x.setCard(j.getCard());
                        x.setIdFront(j.getIdFront());
                        x.setIdOpposite(j.getIdOpposite());
                        x.setThreeSyndromesInOne(j.getThreeSyndromesInOne());
                        x.setBusinessUrl(j.getBusinessUrl());
                        x.setCreditCode(j.getCreditCode());
                        x.setValidity(j.getValidity());
                        x.setValidityTime(j.getValidityTime());
                    }
                    x.setSourceData(null);
                }
            });
        }

        return PageDataUtil.getPageData(res, QueryMallStoreAuditListRes.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Lock(ce = LockCategoryEnum.ID,value = "MALL:AUDIT",field = "mallId",expire = 3l)
    public Boolean mallStoreAuditDro(MallStoreAuditDroReq req) {
        Integer adminUserId = AppLoginTokenRedis.me().getAdminUserInfoRes().getAdminUserId();
        LambdaQueryWrapper<AppMallInfo> lqwami = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AppMallAudit> lqwama = new LambdaQueryWrapper<>();
        if (ConstantsValue.I_1.equals(req.getAuditType())){
            lqwami.eq(AppMallInfo::getId,req.getMallId()).eq(AppMallInfo::getState,ShopStateEnum.IN_REVIEW.getCode())
                    .orderByDesc(AppMallInfo::getId).last("limit 1");


            lqwama.eq(AppMallAudit::getMallId,req.getMallId())
                    .eq(AppMallAudit::getType,ConstantsValue.I_1)
                    .orderByDesc(AppMallAudit::getId).last("limit 1");

        }
        // 正常状态下进行主体信息修改
        else {
            lqwami.eq(AppMallInfo::getId,req.getMallId()).eq(AppMallInfo::getState,ShopStateEnum.PASS.getCode())
                    .orderByDesc(AppMallInfo::getId).last("limit 1");

            lqwama.eq(AppMallAudit::getMallId,req.getMallId())
                    .eq(AppMallAudit::getType,ConstantsValue.I_3)
                    .orderByDesc(AppMallAudit::getId).last("limit 1");

        }
        AppMallInfo ami = appMallInfoMapper.selectOne(lqwami);
        if (ObjectUtils.isEmpty(ami)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_011);
        }



        AppMallAudit ama =  appMallAuditMapper.selectOne(lqwama);
        if (ObjectUtils.isEmpty(ama)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_016);
        }
        ShopStateEnum shopStateEnum = ShopStateEnum.getInstance(req.getState());
        if (shopStateEnum == ShopStateEnum.FAIL && (StringUtils.isBlank(req.getReason()) || CollectionUtils.isEmpty(req.getProblemFields()))){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_015);
        }

        AdminMallConfig adminMallConfig = adminMallConfigMapper.selectById(ConstantsValue.I_1);
        if (ObjectUtils.isEmpty(adminMallConfig)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_044);
        }

        AppMallAudit updateAma = new AppMallAudit();
        updateAma.setId(ama.getId());
        updateAma.setAuditState(req.getState());
        updateAma.setReason(req.getReason());
        updateAma.setProblemList(JSON.toJSONString(req.getProblemFields()));
        updateAma.setOperator(adminUserId);
        appMallAuditMapper.updateById(updateAma);



        AppMallInfo updateAmi = new AppMallInfo();
        updateAmi.setId(req.getMallId());
        // todo 专门处理名称和logo
        if (ShopStateEnum.PASS.getCode().equals(req.getState())){
            if (ObjectUtils.isNotEmpty(ami.getMallName()) && ObjectUtils.isEmpty(ami.getEcommerceName())){
                updateAmi.setEcommerceName(ami.getMallName());
            }
            if (ObjectUtils.isNotEmpty(ami.getLogo()) && ObjectUtils.isEmpty(ami.getEcommerceLogo())){
                updateAmi.setEcommerceLogo(ami.getLogo());
            }
        }


        if (ConstantsValue.I_1.equals(req.getAuditType())){

            updateAmi.setState(req.getState());
            // 审核通过
            if (ShopStateEnum.PASS.getCode().equals(req.getState())){
                LambdaQueryWrapper<AppMallAccount> lqwamacc = new LambdaQueryWrapper<>();
                lqwamacc.eq(AppMallAccount::getMallId,ami.getId()).eq(AppMallAccount::getUserId,ami.getUserId());
                AppMallAccount appMallAccount = appMallAccountMapper.selectOne(lqwamacc);
                if (ObjectUtils.isEmpty(appMallAccount)){
                    appMallAccount = new AppMallAccount();
                    appMallAccount.setMallId(ama.getMallId());
                    appMallAccount.setUserId(ami.getUserId());
//                    appMallAccount.setCollectAddress(ami.getCollectAddress());
                    appMallAccount.setContributing(BigDecimal.ZERO);
                    appMallAccountMapper.insert(appMallAccount);
                }
                LambdaQueryWrapper<AppMallStatistics> lqwams = new LambdaQueryWrapper<>();
                lqwams.eq(AppMallStatistics::getMallId,appMallAccount.getMallId());
                AppMallStatistics appMallStatistics = appMallStatisticsMapper.selectOne(lqwams);
                if (ObjectUtils.isEmpty(appMallStatistics)){
                    appMallStatistics = new AppMallStatistics();
                    appMallStatistics.setMallId(appMallAccount.getMallId());
                    appMallStatisticsMapper.insert(appMallStatistics);
                }

                if (StringUtils.isBlank(ami.getNumber())){
                    updateAmi.setNumber(UniqueIDUtils.getUid("", req.getMallId(),true));
                }
                if (ami.getLevel() < adminMallConfig.getPersonalInitLevel()){
                    if (ObjectUtils.isNotEmpty(ami.getIsBusiness()) && ConstantsValue.I_1.equals(ami.getIsBusiness()) ){
                        updateAmi.setLevel(adminMallConfig.getBusinessInitLevel());
                    }else {
                        updateAmi.setLevel(adminMallConfig.getPersonalInitLevel());
                    }
                }else {
                    updateAmi.setLevel(ami.getLevel());
                }
                //审核通过  赠送加速卡
               // addCard(ami.getUserId(),ami.getIsBusiness());

            }
            appMallInfoMapper.updateById(updateAmi);
        }else {
            if (ShopStateEnum.PASS.getCode().equals(req.getState())){
                LambdaQueryWrapper<AppMallDocumentInfo> lqwAmdi = new LambdaQueryWrapper<>();
                lqwAmdi.eq(AppMallDocumentInfo::getMallId,ami.getId());
                AppMallDocumentInfo amdi = appMallDocumentInfoMapper.selectOne(lqwAmdi);
                if (ObjectUtils.isEmpty(amdi)){
                    throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_010);
                }
                AppMallDocumentInfo updateAmdi = JSONObject.parseObject(ama.getSourceData(),AppMallDocumentInfo.class);
                float level = 0;
                if (ObjectUtils.isNotEmpty(updateAmdi.getIsBusiness()) && ConstantsValue.I_1.equals(updateAmdi.getIsBusiness()) ){
                    level = adminMallConfig.getBusinessInitLevel();
                }else {
                    level = adminMallConfig.getPersonalInitLevel();
                }
                if (!ami.getLevel().equals(level)){
                    updateAmi.setIsBusiness(updateAmdi.getIsBusiness());
                    updateAmi.setLevel(level);
                    appMallInfoMapper.updateById(updateAmi);
                }
                updateAmdi.setId(amdi.getId());
                appMallDocumentInfoMapper.updateById(updateAmdi);
                if (ObjectUtils.isEmpty(updateAmi.getLevel())){
                    updateAmi.setLevel(level);
                }

                //审核通过  赠送加速卡
              //  addCard(ami.getUserId(),updateAmi.getIsBusiness());
            }




        }



        // 下面处理星推官等级
        if (ShopStateEnum.PASS.getCode().equals(req.getState())){
//            // 看看有没有历史审核成功的记录，如果有不影响星推官等级 如果没有要计算星推官等级
//            LambdaQueryWrapper<AppMallAudit> lqwama2 = new LambdaQueryWrapper<>();
//            lqwama2.eq(AppMallAudit::getAuditState,ConstantsValue.I_1).eq(AppMallAudit::getMallId,ama.getId()).ne(AppMallAudit::getId,updateAma.getId());
//            if (appMallAuditMapper.selectCount(lqwama2) <= 0){
            LambdaQueryWrapper<AdminMallPromotion> lqwamp = new LambdaQueryWrapper<>();
            lqwamp.eq(AdminMallPromotion::getState,ConstantsValue.I_0)
                    .select(AdminMallPromotion::getMallLevel,AdminMallPromotion::getMinLevel,AdminMallPromotion::getMaxLevel,AdminMallPromotion::getMallNum)
                    .orderByDesc(AdminMallPromotion::getUpdateTime).last("limit 1");
            AdminMallPromotion amp = adminMallPromotionMapper.selectOne(lqwamp);
            if (ObjectUtils.isEmpty(amp)) {
                log.info("星推官配置不存在!");
                return Boolean.TRUE;
            }

            LambdaQueryWrapper<AppUser> lqwau = new LambdaQueryWrapper<>();
            lqwau.eq(AppUser::getId, ama.getUserId())
                    .isNotNull(AppUser::getInviterId)
                    .gt(AppUser::getInviterId,ConstantsValue.I_0).select(AppUser::getInviterId,AppUser::getId);
            AppUser appUser = appUserMapper.selectOne(lqwau);
            if (ObjectUtils.isEmpty(appUser)){
                log.info("用户没有邀请人!");
                return Boolean.TRUE;
            }

            LambdaQueryWrapper<AppMallPromotionIds> lqwampi = new LambdaQueryWrapper<>();
            lqwampi.eq(AppMallPromotionIds::getBelowMallUserId,appUser.getId())
                    .eq(AppMallPromotionIds::getUserId,appUser.getInviterId());
            if (null != appMallPromotionIdsMapper.idIsExists(appUser.getInviterId(),appUser.getId())){
                log.info("用户{} 和 {} 已经存在星推官绑定关系!",appUser.getId(),appUser.getInviterId());
                return Boolean.TRUE;
            }


            if (updateAmi.getLevel() >= amp.getMallLevel()){
                LambdaQueryWrapper<AppMallPromotion> lqwamp1 = new LambdaQueryWrapper<>();
                lqwamp1.eq(AppMallPromotion::getUserId,appUser.getInviterId()).eq(AppMallPromotion::getState,ConstantsValue.I_0);
                AppMallPromotion appMallPromotion = appMallPromotionMapper.selectOne(lqwamp1);

                LevelUpHistory history = new LevelUpHistory();
                Boolean needLevelUp = false;
                Integer before = ConstantsValue.I_0;
                Integer after = ConstantsValue.I_0;

                if (ObjectUtils.isEmpty(appMallPromotion)){
                    appMallPromotion = new AppMallPromotion();
                    appMallPromotion.setUserId(appUser.getInviterId());
                    appMallPromotion.setMallNum(ConstantsValue.I_1);
                    appMallPromotion.setLevel(appMallPromotion.getMallNum()/amp.getMallNum());
                    appMallPromotionMapper.insert(appMallPromotion);
                    if (appMallPromotion.getLevel()> ConstantsValue.I_0){
                        needLevelUp = true;
                        after = appMallPromotion.getLevel();
                    }

                }else {
                    AppMallPromotion updateAmp = new AppMallPromotion();
                    updateAmp.setId(appMallPromotion.getId());
                    updateAmp.setMallNum(appMallPromotion.getMallNum() + ConstantsValue.I_1);
                    updateAmp.setLevel(updateAmp.getMallNum()/amp.getMallNum());
                    if (updateAmp.getLevel() >= amp.getMaxLevel()){
                        log.info("用户 {} 已经达到最大等级了",updateAmp.getUserId());
                        updateAmp.setLevel(amp.getMaxLevel());
                    }

                    appMallPromotionMapper.updateById(updateAmp);
                    if (!appMallPromotion.getLevel().equals(updateAmp.getLevel())){
                        before = appMallPromotion.getLevel();
                        needLevelUp = true;
                        after = updateAmp.getLevel();
                    }
                }
                AppMallPromotionIds appMallPromotionIds = new AppMallPromotionIds();
                appMallPromotionIds.setBelowMallUserId(appUser.getId());
                appMallPromotionIds.setUserId(appUser.getInviterId());
                appMallPromotionIds.setMallLevel(updateAmi.getLevel());
                appMallPromotionIdsMapper.insert(appMallPromotionIds);



                if (needLevelUp){
                    history.setType(LevelUpTypeEnum.PROMOTION.ordinal());
                    history.setUserId(appMallPromotion.getUserId());
                    history.setBeforeLevel(before);
                    history.setAfterLevel(after);
                    history.setReason("管理台下级商家审核通过触发");
                    levelUpHistoryMapper.insert(history);
                }
            }
//            }
        }


        return ConstantsValue.TRUE;
    }








    @Override
    public PageData<MallStoreImgAuditRes> queryMallStoreAuditBgImageList(QueryMallStoreAuditListReq req) {
        Page<MallStoreImgAuditRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<MallStoreImgAuditRes> res = appMallAuditMapper.getAuditBgImageRecord(page,req);
        return PageDataUtil.getPageData(res);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @Lock(ce = LockCategoryEnum.ID,value = "MALL:BG_AUDIT",field = "mallId",expire = 3l)
    public Boolean mallStoreAuditBgImageDro(MallStoreAuditImageReq req) {
        LambdaQueryWrapper<AppMallAudit> lqwama = new LambdaQueryWrapper<>();
        lqwama.eq(AppMallAudit::getMallId,req.getMallId())
                .eq(AppMallAudit::getType,ConstantsValue.I_2)
                .eq(AppMallAudit::getAuditState,ShopStateEnum.IN_REVIEW.getCode())
                .orderByDesc(AppMallAudit::getId).last("limit 1");
        AppMallAudit ama =  appMallAuditMapper.selectOne(lqwama);
        if (ObjectUtils.isEmpty(ama)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_016);
        }
        AppMallAudit updateAma = new AppMallAudit();
        updateAma.setId(ama.getId());
        updateAma.setAuditState(req.getState());
        updateAma.setReason(req.getReason());
        appMallAuditMapper.updateById(updateAma);

        if (ShopStateEnum.PASS.getCode().equals(req.getState())){
            AppMallInfo update = new AppMallInfo();
            update.setId(req.getMallId());
            update.setBgImage(ama.getSourceData());
            appMallInfoMapper.updateById(update);
        }

        return ConstantsValue.TRUE;
    }


    @Override
    public Boolean mallStoreBannerSaveAndUpdate(MallStoreBannerReq req) {
        AppMallBanner appMallBanner = new AppMallBanner();
        BeanUtils.copyProperties(req,appMallBanner);
        if (ObjectUtils.isNotEmpty(appMallBanner)){
            LambdaQueryWrapper<AppMallBanner> lqwamb = new LambdaQueryWrapper<>();
            if (ObjectUtils.isNotEmpty(appMallBanner.getId())){
                lqwamb.eq(AppMallBanner::getUrl,req.getUrl()).ne(AppMallBanner::getId,req.getId());
                if (appMallBannerMapper.selectCount(lqwamb) > 0){
                    throw new ApiServiceException("已经存在该图片的Banner");
                }
                appMallBannerMapper.updateById(appMallBanner);
            }else {
                lqwamb.eq(AppMallBanner::getUrl,req.getUrl());
                if (appMallBannerMapper.selectCount(lqwamb) > 0){
                    throw new ApiServiceException("已经存在该图片的Banner");
                }
                appMallBannerMapper.insert(appMallBanner);
            }
        }
        return true;
    }


    @Override
    public Boolean mallStoreBannerPush(MallStoreBannerPushReq req) {
        AppMallBanner a = appMallBannerMapper.selectById(req.getId());
        if (ObjectUtils.isEmpty(a)){
            throw new ApiServiceException("记录不存在");
        }
        AppMallBanner u = new AppMallBanner();
        u.setId(a.getId());
        if (ConstantsValue.I_1.equals(a.getState())){
            u.setState(ConstantsValue.I_0);
        }else
            u.setState(ConstantsValue.I_1);

        appMallBannerMapper.updateById(u);
        return true;
    }



    @Override
    public PageData<MallStoreListRes> mallStoreList(MallStoreListReq req) {
        Page<MallStoreListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<MallStoreListRes> res = appMallAuditMapper.mallStoreList(page,req);
        String date = DateUtil.format(new Date(),"yyyy-MM-dd");
        if (!CollectionUtils.isEmpty(res.getRecords())){
            res.getRecords().forEach(x->{
                String c = (String) redisService.opsForHash().get(String.format(RedisKeyConstant.APP_MALL_STATISTICS_TURNOVER,date),String.valueOf(x.getMallId()));
                BigDecimal ct = StringUtils.isBlank(c) ? BigDecimal.ZERO : new BigDecimal(c);
                AppMallStatistics ams = appMallStatisticsMapper.selectByMallId(x.getMallId());
                QueryWrapper<AppMallCardInfo> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("user_id", x.getUserId()).gt("expired_time",LocalDateTime.now()).eq("state",1);
                x.setCardCount(appMallCardInfoMapper.selectCount(queryWrapper1));
                if (ObjectUtils.isNotEmpty(ams))
                    x.setTurnover(ams.getTurnover());
                if (ObjectUtils.isEmpty(x.getTurnover()))
                    x.setTurnover(BigDecimal.ZERO);

                x.setTurnover(x.getTurnover().add(ct));
                if (x.getIsBusiness().equals(ConstantsValue.I_1)){
                    x.setDisplaySettleIn("个体商店");
                }else{
                    x.setDisplaySettleIn("个人店");
                }
                x.setDisplayCategory(x.getOneCategoryName() + "/" + x.getTwoCategoryName());
            });
        }
        return PageDataUtil.getPageData(res);
    }


    @Autowired
    AppUserAssetsHistoryMapper appUserAssetsHistoryMapper;

    @Override
    public PageData<MallStoreAccountListRes> storeAccountList(MallStoreAccountListReq req) {
        Page<MallStoreAccountListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<MallStoreAccountListRes> res = appUserAssetsHistoryMapper.storeAccountList(page,req);
        if (!CollectionUtils.isEmpty(res.getRecords())){
            res.getRecords().forEach(x->{
                x.setDisplayCategory(x.getOneCategoryName() + "/" + x.getTwoCategoryName());
            });
        }
        return PageDataUtil.getPageData(res);
    }

    @Override
    public MallStoreStaticRes statisticsData() {
        MallStoreStaticRes res = new MallStoreStaticRes();
        res.setPersonal(appMallStatisticsMapper.staticStorePersonal());
        res.setBalance(appMallStatisticsMapper.staticStoreBalance());
        res.setStores(appMallStatisticsMapper.staticStoreNumber());
        res.setEnterpriseNum(appMallStatisticsMapper.staticStoreEnterpriseNum());
        res.setTurnover(appMallStatisticsMapper.staticStoreTurnover());
        return res;
    }

    public void addCard(Integer userId,Integer isBusiness){
        QueryWrapper<AppMallCardInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("type",2);
        Integer count = appMallCardInfoMapper.selectCount(queryWrapper);
        AdminCardConfig adminCardConfig = adminCardConfigMapper.selectById(1);
        int i;
        if(ConstantsValue.I_1.equals(isBusiness)){
          i = count < adminCardConfig.getMerchant() ? adminCardConfig.getMerchant()-count:0;
        }else{
            i = count < adminCardConfig.getPersonal() ? adminCardConfig.getPersonal()-count:0;
        }
        if(i>0){
            for (int j = 0; j < i; j++) {
                AppMallCardInfo appMallCardInfo = new AppMallCardInfo();
                appMallCardInfo.setUserId(userId);
                appMallCardInfo.setState(1);
                appMallCardInfo.setDeadline(adminCardConfig.getShelfLife());
                appMallCardInfo.setCreateTime(LocalDateTime.now());
                appMallCardInfo.setAcceleration(adminCardConfig.getAccelerationTime());
                appMallCardInfo.setExpiredTime(appMallCardInfo.getCreateTime().plusDays(adminCardConfig.getShelfLife()));
                appMallCardInfo.setType(2);
                appMallCardInfoMapper.insert(appMallCardInfo);
            }
        }
    }





    @Override
    @Transactional
    public void logOffAudit(MallLogOffReq req) {
        AppMallAudit audit = appMallAuditMapper.selectById(req.getId());
        if (ObjectUtils.isEmpty(audit) || !ConstantsValue.I_0.equals(audit.getAuditState())){
            throw new ApiServiceException("审核记录不存在");
        }
        AppMallAccount account = appMallAccountMapper.selectByMallId(audit.getMallId());
        if (ObjectUtils.isEmpty(account)){
            throw new ApiServiceException("商家账户记录不存在");
        }
        Token token = tokenMapper.selectById(LetokenTokenTypeEnum.CAP.getId());
        if (ObjectUtils.isEmpty(token)){
            throw new ApiServiceException("币种账户记录不存在");
        }
        AppMallInfo appMallInfo = new AppMallInfo();
        appMallInfo.setId(account.getMallId());

        AppMallAudit appMallAudit = new AppMallAudit();
        appMallAudit.setId(audit.getId());
        appMallAudit.setAuditState(req.getState());
        appMallAudit.setReason(req.getReason());


        // 审核通过
        if (ConstantsValue.I_1.equals(req.getState()) ){
            BigDecimal amount = account.getUsdtValue().divide(new BigDecimal(token.getUsdPrice()),4);
            Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.CAP.getId(), account.getUserId());
            if (ObjectUtils.isEmpty(walletId)){
                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_051);
            }
            AppUserWallet w = appUserWalletMapper.selectForUpdate(walletId);
            if (w.getAvailableBalance().compareTo(BigDecimal.ZERO) < 0){
                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_053);
            }

            AppUserWallet updateW = new AppUserWallet();
            updateW.setId(w.getId());
            updateW.setAvailableBalance(w.getAvailableBalance().add(amount));
            appUserWalletMapper.updateById(updateW);


            String seqNo = UniqueIDUtils.genSeqNo("BO");
            AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
            assetHistory.setUserId(account.getUserId());
            assetHistory.setType(TokenTransactionTypeEnum.MALL_REFUND_BOND.getValue());
            assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
            assetHistory.setTokenId(LetokenTokenTypeEnum.CAP.getId());
            assetHistory.setAmount(amount);
            assetHistory.setSn(seqNo);
            assetHistory.setBalance(updateW.getAvailableBalance());
            assetHistory.setCreateTime(LocalDateTime.now());
            assetHistory.setUpdateTime(assetHistory.getCreateTime());
            appUserAssetsHistoryMapper.insert(assetHistory);

            appMallInfo.setState(ShopStateEnum.LOG_OFF.getCode());
        }else {
            appMallInfo.setState(ShopStateEnum.PASS.getCode());
            appMallInfo.setPublishState(0);
        }


       appMallInfoMapper.updateById(appMallInfo);
       appMallAuditMapper.updateById(appMallAudit);


    }
}
